package pub.tbc.toolkit.web.config;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pub.tbc.toolkit.Objs;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author tbc tianbencai@e-eduspace.com
 * @version 1.0 {2016年5月18日 下午2:53:35}
 */
public class Config {
    private static Logger log = LoggerFactory.getLogger(Config.class);

    private static final Map<String, PropertiesConfiguration> configs = Maps.newHashMap();

    public static void add(String name, PropertiesConfiguration pc) {
        configs.put(name, pc);
    }

    public static Configuration getConfig() {
        return getConfig("config");
    }

    public static Configuration getConfig(String config) {
        if (Objs.isEmpty(configs.get(config))) {
            synchronized (configs) {
                if (Objs.isEmpty(configs.get(config))) {
                    try {
                        PropertiesScan.scan();
                    } catch (Exception e) {
                        log.error("扫描配置文件出现异常：{}", e.getMessage());
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            }
        }
        return configs.get(config);
    }

    public static Set<String> fileList() {
        return configs.keySet();
    }

    public static ArrayList<String> propKeysByFile(String configFile) {
        Configuration config = configs.get(configFile);
        fileIsExist(config);
        return Lists.newArrayList(config.getKeys());
    }

    public static Map<String, String> propsByFile(String configFile) {
        Configuration config = configs.get(configFile);
        fileIsExist(config);
        Map<String, String> map = Maps.newHashMap();
        List<String> keys = Lists.newArrayList(config.getKeys());
        for (String it : keys) {
            map.put(it, config.getString(it));
        }
        return map;
    }

    public static void setProper(String configFile, String propName, String value) {
        PropertiesConfiguration config = configs.get(configFile);
        fileIsExist(config);
        config.setProperty(propName, value);
        try {
            config.save();
        } catch (ConfigurationException e) {
            log.error("保存配置文件出现异常 ：{} ", e.getMessage());
            throw new RuntimeException("配置保存失败", e);
        }

    }

    public static void refresh() {
        PropertiesScan.scan();
    }

    private static void fileIsExist(Configuration config) {
        if (null == config) {
            throw new RuntimeException("该配置文件不存在");
        }
    }

}
